
import _thread as thread
import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time

import websocket  # 使用websocket_client

class SparkAPI:
    def __init__(self, appid, api_key, api_secret, spark_url, domain="x1"):
        """初始化SparkAPI客户端"""
        self.appid = appid
        self.api_key = api_key
        self.api_secret = api_secret
        self.spark_url = spark_url
        self.domain = domain
        self.answer = ""
        self.current_answer = ''
        self.is_first_content = False
        self.text = [{
            "role": "system",
            "content": """我在做一个机械臂接入大模型的项目。我会给出指令，提取指令中的关键词并转化为json格式输出,只用输出json格式数据即可，不要加其他文本内容。输出JSON格式：
            [{ "object": "", "target_pos": ""}]，target_pos默认为hand,如果指令中有说明则改为指令中提到的。例如“帮我拿个星球杯、喜之郎和碗仔面”,
            返回[{"object": "星球杯", "target_pos": "hand"},{"object": "喜之郎", "target_pos": "hand"},{"object": "碗仔面", "target_pos": "hand"}]，“帮我把星球杯放在喜之郎上”，
            返回[{"object": "星球杯", "target_pos": "喜之郎"}]，以下是目标映射表：{"酪酪杯":"laolaobei","豆干":"dougan","喜之郎":"xizhilang","生椰拿铁":"shengyenatie","碗仔面":"wanzaimian","亲嘴烧":"qinzuishao","水蜜桃果汁":"shuimitaoguozhi","星球杯":"xingqiubei","奶酪小丸子":"nailaoxiaowanzi"}
            输出的object和target_pos全部映射到我给的映射表中的拼音。文字输入可能会有读音上的偏差，比如“唠唠呗”、“乐乐杯”等指的是"酪酪杯"，“果冻”指的是“喜之郎”，“方便面”指的是“碗仔面”，请减少思考时间."""
        }]
        
    def create_url(self):
        """生成带签名的请求URL"""
        host = urlparse(self.spark_url).netloc
        path = urlparse(self.spark_url).path
        
        # 生成RFC1123格式的时间戳
        now = datetime.now()
        date = format_date_time(mktime(now.timetuple()))

        # 拼接字符串
        signature_origin = "host: " + host + "\n"
        signature_origin += "date: " + date + "\n"
        signature_origin += "GET " + path + " HTTP/1.1"

        # 进行hmac-sha256进行加密
        signature_sha = hmac.new(
            self.api_secret.encode('utf-8'), 
            signature_origin.encode('utf-8'),
            digestmod=hashlib.sha256
        ).digest()

        signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')

        authorization_origin = (
            f'api_key="{self.api_key}", '
            f'algorithm="hmac-sha256", '
            f'headers="host date request-line", '
            f'signature="{signature_sha_base64}"'
        )

        authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')

        # 将请求的鉴权参数组合为字典
        v = {
            "authorization": authorization,
            "date": date,
            "host": host
        }
        # 拼接鉴权参数，生成url
        url = self.spark_url + '?' + urlencode(v)
        return url
    
    def _on_error(self, ws, error):
        """收到websocket错误的处理"""
        print("### error:", error)

    def _on_close(self, ws, close_status_code, close_msg):
        """收到websocket关闭的处理"""
        print(" ")

    def _on_open(self, ws):
        """收到websocket连接建立的处理"""
        thread.start_new_thread(self._run, (ws,))

    def _run(self, ws, *args):
        """发送请求数据"""
        data = json.dumps(self._gen_params(question=ws.question))
        ws.send(data)

    def _on_message(self, ws, message):
        """收到websocket消息的处理"""
        data = json.loads(message)
        code = data['header']['code']
        content = ''
        
        if code != 0:
            print(f'请求错误: {code}, {data}')
            ws.close()
        else:
            choices = data["payload"]["choices"]
            status = choices["status"]
            text = choices['text'][0]
            
            if 'reasoning_content' in text and text['reasoning_content'] != '':
                reasoning_content = text["reasoning_content"]
                print(reasoning_content, end="")
                self.is_first_content = True

            if 'content' in text and text['content'] != '':
                content = text["content"]
                self.current_answer = content
                if self.is_first_content:
                    print("\n*******************以上为思维链内容，模型回复内容如下********************\n")
                print(content, end="")
                self.is_first_content = False
                
            self.answer += content
            
            if status == 2:
                ws.close()

    def _gen_params(self, question):
        """生成请求参数"""
        data = {
            "header": {
                "app_id": self.appid,
                "uid": "1234",
            },
            "parameter": {
                "chat": {
                    "domain": self.domain,
                    "temperature": 1.2,
                    "max_tokens": 32768  # 请根据不同模型支持范围，适当调整该值的大小
                }
            },
            "payload": {
                "message": {
                    "text": question
                }
            }
        }
        return data
    
    def _get_text(self, role, content):
        """管理对话历史，按序编为列表"""
        jsoncon = {"role": role, "content": content}
        self.text.append(jsoncon)
        return self.text

    def _get_length(self, text):
        """获取对话中的所有角色的content长度"""
        length = 0
        for content in text:
            temp = content["content"]
            leng = len(temp)
            length += leng
        return length

    def _check_len(self, text):
        """判断长度是否超长，当前限制8K tokens"""
        while self._get_length(text) > 8000:
            del text[0]
        return text
    
    def chat(self, user_input):
        """与星火大模型对话"""
        self.answer = ""  # 清空上次回答
        question = self._check_len(self._get_text("user", user_input))
        print("星火:", end="")
        
        ws_url = self.create_url()
        ws = websocket.WebSocketApp(
            ws_url,
            on_message=self._on_message,
            on_error=self._on_error,
            on_close=self._on_close,
            on_open=self._on_open
        )
        ws.question = question
        ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
        
        self._get_text("assistant", self.answer)
        return self.answer


if __name__ == '__main__':
    # 以下密钥信息从服务管控页面获取：https://console.xfyun.cn/services/bmx1
    appid = "72b9a0ad"  # 填写控制台中获取的 APPID 信息
    api_secret = "NmMyYTRlZjFhMmZkN2FkZjg0ODQ5NDVl"  # 填写控制台中获取的 APISecret 信息
    api_key = "59958ac9ffdaed40d02509f4bb593774"  # 填写控制台中获取的 APIKey 信息
    domain = "x1"       # 控制请求的模型版本
    # 服务地址
    spark_url = "wss://spark-api.xf-yun.com/v1/x1"  # 查看接口文档  https://www.xfyun.cn/doc/spark/X1ws.html

    # 创建API客户端
    client = SparkAPI(appid, api_key, api_secret, spark_url, domain)

    # 简单对话循环
    while True:
        user_input = input("\n我: ")
        if user_input.lower() in ["exit", "quit", "bye"]:
            break
        client.chat(user_input)